package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.TurnoverReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
       //当前集合用于存放begin-end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期加1
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //得到日期集合并封装到vo中去
        //可以使用工具类StringUtils.join,就是把detelist中的元素用逗号连接起来拼成字符串
        String dateList1 = StringUtils.join(dateList, ",");

        //统计已完成的订单金额
        List<Double> turnoverList = new ArrayList<>();
        //要查每天对应的营业额 所以要遍历日期结合
        for(LocalDate date : dateList){
            //创建时间 因为查询的开始时间是00:00:00 要精确到时分秒
            //用于判断订单是否在某个时间段内要大于beginTime 小于endTime
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //因为条件有三个所以可以封装到map里面
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //获取营业额
           Double turnover =  orderMapper.sumByMap(map);
           //把营业额添加到list中
           turnoverList.add(turnover);
        }
        String turnoverList1 = StringUtils.join(turnoverList, ",");


        //结果封装
        TurnoverReportVO turnoverReportVO = TurnoverReportVO
                .builder()
                .dateList(dateList1)
                .turnoverList(turnoverList1)
                .build();


        return turnoverReportVO;
    }
}
